import { getSetting,openSetting,chooseAddress,showModal,showToast } from "../../utils/asyncWX";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        addressShow:{},
        cart:[],
        checkedAll:false,
        totalPrice:0,
        totalNum:0
    },
    /* 生命周期函数--监听页面显示 */
     onShow: function (options) {
        let addressShow = wx.getStorageSync('address');
        let cart = wx.getStorageSync('cart')||[];
        this.SetCart(cart)
        this.setData({
            addressShow
        })
    },
    /* 点击收货地址 */
    async handleChooseAddress(){
        /* 获取权限状态，回调地狱了 */
        /* wx.getSetting({
            success: (result)=>{
                // 查看权限状态 
                const scopeAddress = result.authSetting['scope.address']
                if (scopeAddress===true||scopeAddress===undefined) {
                    wx.chooseAddress({
                        success: (result1)=>{
                            console.log(result1);
                        }
                    });
                } else {
                    // 之前拒绝过的，诱导打开权限 
                    wx.openSetting({
                        success: (result2)=>{
                            wx.chooseAddress({
                                success: (result3)=>{
                                    console.log(result3);
                                }
                            });
                        }
                    })
                }
            }
        }); */
        
        try {
            /* 获取权限 */
            const res1 = await getSetting()
            const scopeAddress = res1.authSetting['scope.address']
            /* 判断状态 */
            if (scopeAddress===false) {
                await openSetting()
            }
            /* 调取收货地址api */
            const add = await chooseAddress()
            /* 把获取到的地址存入缓存 */
            add.all = add.provinceName+add.cityName+add.countyName+add.detailInfo
            wx.setStorageSync("address", add);
            console.log(add);
        } catch (error) {
            console.log(error);
        }
    },
    /* 判断全选与价格与数量 */
    SetCart(cart){
        /* 遍历数组的每个选中，用every，全对才返回对 */
        //let checkedAll = cart.length?cart.every(v=>v.checked):false
        let totalPrice = 0
        let totalNum = 0
        let checkedAll = true
        /* 直接在这次遍历中加入 全选判断 */
        /* forEach ()方法没有返回值，会修改原来的数组 */
        cart.forEach(v => {
            if (v.checked) {
                totalPrice += v.goods_price*v.num
                totalNum += v.num
            }else{
                checkedAll = false
            }
        });
        /* 判断数组是否为空 */
        checkedAll = cart.length!=0?checkedAll:false
        this.setData({
            cart,
            checkedAll,
            totalPrice,
            totalNum
        })
        wx.setStorageSync('cart',cart);
    },
    /* 点击选中按钮 切换全选与否*/
    handleChecked(e){
        /* 先设置id，获取id */
        let gid = e.currentTarget.dataset.id
        /* 使用数据需要 用this.data.cart，findIndex（）查找索引需加回调函数，返回在数组中的索引*/
        let {cart} = this.data
        /* 到数组中查找id */
        let index = cart.findIndex(v=>v.goods_id===gid)
        cart[index].checked = !cart[index].checked
        wx.setStorageSync('cart',cart)
        this.SetCart(cart)
    },
    /* 点全选，其他选项跟着改变 */
    handleAllchecked(){
        let {cart,checkedAll} = this.data
        checkedAll = !checkedAll
        cart.forEach(v=>v.checked=checkedAll)
        this.SetCart(cart)
    },
    /* 点击增减数量 */
    async handleClickNum(e){
        let {id,oper} = e.currentTarget.dataset
        let {cart} = this.data
        let index = cart.findIndex(v=>v.goods_id===id)
        if (cart[index].num===1&&oper===-1) {
            /* wx.showModal({
                title: '提示',
                content: '是否要删除',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确定',
                confirmColor: '#3CC51F',
                success: (result) => {
                    if (result.confirm) {
                        
                    }
                },
                fail: () => {},
                complete: () => {}
            }); */
            const res = await showModal("是否要删除")
            if (res.confirm) {
                cart.splice(index,1)
                this.SetCart(cart)
            }
        }else{
            cart[index].num += oper
            this.SetCart(cart)
        }

    },
    async handlePay(){
        let {addressShow,totalNum} = this.data
        if (!addressShow.cityName) {
            await showToast('未填写收货地址')
            return
        }
        if (!totalNum) {
            await showToast('暂无商品')
            return
        }
        wx.navigateTo({
            url: '/pages/pay/pay'
        });
          
    }
})